import { defineStore } from "pinia";
import { useLocationParams } from "@/store/useLocationStore";
import {
  RouteComponent,
  RouteLocationNormalizedLoadedGeneric,
  useRouter
} from "vue-router";
import { objToQueryString } from "@/utils/url";
import { useUserStore } from "./useUserStore";
import { generatesignature } from "@/utils/crypto";
import { http } from "@/utils/http";
const authHeaders = generatesignature();
export async function initDomain() {
  try {
    const data = await http.request<string>({
      url: "/login/auth_domain",
      headers: { "No-Auth": true },
      method: "GET",
      params: authHeaders
    });
    domain = data;
  } catch (error) {
    console.log(error);
  }
}
export let domain: string | null = null;
export const useAuthStore = defineStore("auth", () => {
  const { getAllParams } = useLocationParams();
  let redirectUrl = domain + "/userweb/login";

  const handleAuth = async (
    fromRoute: RouteLocationNormalizedLoadedGeneric
  ) => {
    // const allParams = getAllParams();
    // const userStore = useUserStore();
    // if (allParams.code || userStore.isAuthenticated()) {
    //   // 有code进入原有逻辑
    //   return cb && cb(allParams.code);
    // }
    // if (!domain) {
    //   const data: any = await initDomain();
    //   domain = data;
    //   const url = new URL(redirectUrl);
    //   const domainUrl = new URL(domain);
    //   domainUrl.pathname = url.pathname;
    //   redirectUrl = domainUrl.toString();
    // }
    // from 路由作为参数
    const from = `${window.location.origin}${import.meta.env.VITE_PUBLIC_PATH}${fromRoute.path}`;
    delete fromRoute.query.code;
    // query 参数
    const query = objToQueryString({ ...fromRoute.query, from });
    const finalRedirectUrl = `${redirectUrl}?${query}`;
    window.location.href = finalRedirectUrl;
  };

  return {
    handleAuth
  };
});
